<template>
  <div class="main-container">
    <!-- 面包屑 -->
    <div class="breadcrumb">
      <span class="breadcrumb-logo">
        <i class="iconfont icon-tielu"></i>
        <span>12306</span>
      </span>
      <span class="breadcrumb-separator">/</span>
      <span class="breadcrumb-link">
        <i class="iconfont icon-chaxun"></i>
        <span>车票查询</span>
      </span>
    </div>
    <!-- 内容区域 -->
    <div class="main-content">
      <!-- 卡片1 -->
      <div class="card-body">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="出发地">
            <el-select
              v-model="formInline.fromStation"
              placeholder="北京"
              clearable
            >
              <el-option
                v-for="(item, index) in allStations"
                :label="item.name"
                :value="item.code"
                :key="index"
              />
            </el-select>
          </el-form-item>
          <div class="retweet" @click="handleExchange">
            <i class="iconfont icon-retweet"></i>
          </div>
          <el-form-item label="目的地">
            <el-select
              v-model="formInline.toStation"
              placeholder="杭州"
              clearable
            >
              <el-option
                v-for="(item, index) in allStations"
                :label="item.name"
                :value="item.code"
                :key="index"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="出发日">
            <el-config-provider :locale="locale">
              <el-date-picker
                v-model="formInline.departureDate"
                type="date"
                placeholder="请选择日期"
                clearable
              />
            </el-config-provider>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchHandle">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 卡片2 -->
      <div class="card-body2">
        <el-tabs type="border-card" v-model="activeName">
          <el-tab-pane
            v-for="(item, index) in days"
            :label="
              index === activeName
                ? item.format('MM-DD  ddd')
                : item.format('MM-DD')
            "
            :name="index"
            :key="index"
            >User</el-tab-pane
          >
        </el-tabs>
        <div class="card-content">
          <div class="content-left">
            <!-- 车次类型多选框 -->
            <div class="trainbrand">
              <span class="title">车次类型</span>
              <el-checkbox
                v-model="checkTrainBrandAll"
                @change="handleCheckTrainBrandAllChange"
                >全部</el-checkbox
              >
              <el-checkbox-group
                v-model="checkedTrainBrand"
                @change="handleCheckedTrainBrandChange"
              >
                <el-checkbox
                  v-for="(brand, index) in trainBrandList"
                  :key="index"
                  :value="brand"
                  >{{ brand }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
            <!-- 出发车站 -->
            <div class="trainbrand">
              <span class="title">出发车站</span>
              <el-checkbox
                v-model="checkDepartureStationAll"
                @change="handleCheckDepartureStationAllChange"
                >全部</el-checkbox
              >
              <el-checkbox-group
                v-model="checkedDepartureStation"
                @change="handleCheckedDepartureStationChange"
              >
                <el-checkbox
                  v-for="(departureStation, index) in departureStationList"
                  :key="index"
                  :value="departureStation"
                  >{{ departureStation }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
            <!-- 到达车站 -->
            <div class="trainbrand">
              <span class="title">出发车站</span>
              <el-checkbox
                v-model="checkArrivalStationAll"
                @change="handleCheckArrivalStationAllChange"
                >全部</el-checkbox
              >
              <el-checkbox-group
                v-model="checkedArrivalStation"
                @change="handleCheckedArrivalStationChange"
              >
                <el-checkbox
                  v-for="(arrivalStation, index) in arrivalStationList"
                  :key="index"
                  :value="arrivalStation"
                  >{{ arrivalStation }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
            <!-- 车次席别 -->
            <div class="trainbrand">
              <span class="title">车次席别</span>
              <el-checkbox
                v-model="checkseatClassTypeListAll"
                @change="handleCheckseatClassTypeListAllChange"
                >全部</el-checkbox
              >
              <el-checkbox-group
                v-model="checkedseatClassTypeList"
                @change="handleCheckedseatClassTypeListChange"
              >
                <el-checkbox
                  v-for="(seatClassTypeList, index) in seatClassTypeList"
                  :key="index"
                  :value="seatClassTypeList"
                  >{{ seatClassTypeList }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
          </div>
          <div class="content-right">
            <span>发车时间</span>
            <el-select
              v-model="carRangeTimeValue"
              class="m-2"
              placeholder="Select"
            >
              <el-option
                v-for="item in carRangeTime"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </div>
      <div class="space-item">
        <span class="city-name">{{ from[0]?.name }}</span>
        <i class="iconfont icon-swap-right"></i>
        <span class="city-name">{{ to[0]?.name }}</span>
        （
        <span class="city-name">{{ formattedTime }}</span>
        ） 共计
        <span class="num" style="font-weight: bold">{{
          trainList.length
        }}</span>
        个车次
      </div>
      <div class="list-table">
        <TrainList :trainList="trainList" />
      </div>
      <div class="description">
        <div>
          如果查询结果中没有满足需求的车次，您还可以使用中转换乘功能，查询途中换乘一次的部分列车余票情况。
        </div>
        <div>
          显示的卧铺票价均为上铺票价，供您参考。具体票价以您确认支付时实际购买的铺别票价为准。如因运力原因或者其他不可控因素导致列车调度调整时，当前车型可能会发生变动。
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import TrainList from "@/views/TrainList/index.vue"
import zhCn from "element-plus/dist/locale/zh-cn.mjs"
import { queryTicket, queryAllStation } from "@/api/ticket"
import { TRAIN_BRAND_LIST, SEAT_CLASS_TYPE_LIST } from "@/constants/index"
import dayjs from "dayjs"
import { computed, onMounted, ref, watch } from "vue"
import "dayjs/locale/zh-cn" // 引入中文语言包
dayjs.locale("zh-cn")

// 当前激活的tab项
let activeName = ref(0)
// 所有的tab项
const days = new Array(15)
  .fill(",")
  .map((item, index) => dayjs().add(index, "days"))

const locale = zhCn

// 获取当前日期并格式化
const formattedDate = dayjs().format("YYYY-MM-DD")
// 所有站点
const allStations = ref([])

// 表单数据
const formInline = ref({
  fromStation: "BJP",
  toStation: "HZH",
  departureDate: formattedDate,
})

// 车票信息
const trainList = ref([])
const trainListTmp = ref([])
// 车次类型
const trainBrandList = ref([])
// 出发车站
const departureStationList = ref([])
// 到达车站
const arrivalStationList = ref([])
// 车次系别
const seatClassTypeList = ref([])

// 发车时间段
const carRangeTime = ref([
  { value: 0, label: "00:00-24:00" },
  { value: 1, label: "00:00-06:00" },
  { value: 2, label: "06:00-12:00" },
  { value: 3, label: "12:00-18:00" },
  { value: 4, label: "18:00-24:00" },
])
const handleExchange = () => {
  const tmp = formInline.value.fromStation
  formInline.value.fromStation = formInline.value.toStation
  formInline.value.toStation = tmp
}
// 当前所选时间段
let carRangeTimeValue = ref(0)
let carRangeTimeValueTmp = computed(() =>
  carRangeTime.value.filter((item) => item.value === carRangeTimeValue.value)
)
//定义总共的判断类型
const judgeType = ref({
  dS: [],
  tBL: [],
  aS: [],
  sCT: [],
})
watch(
  [judgeType, carRangeTimeValueTmp],
  ([val, tvt]) => {
    let listTmp = trainListTmp.value
    if (val.dS.length) {
      listTmp = listTmp.filter((item) =>
        val.dS.some((val) => item.departure === val)
      )
    }
    if (val.tBL.length) {
      listTmp = listTmp.filter((item) =>
        val.tBL.some((brand) => item.trainBrand.includes(brand))
      )
    }
    if (val.aS.length) {
      listTmp = listTmp.filter((item) =>
        val.aS.some((val) => item.arrival === val)
      )
    }
    if (val.sCT.length) {
      console.log(val.sCT)
      listTmp = listTmp.filter((item) =>
        val.sCT.some((val) => item.seatClassList.some((i) => val === i.type))
      )
    }
    if (tvt[0]?.label) {
      listTmp = listTmp.filter((item) =>
        isTimeInRange(item.departureTime, tvt[0]?.label)
      )
    }
    trainList.value = listTmp
  },
  { deep: true }
)
// 判断时间是否在时间段内
function isTimeInRange(timeStr, rangeStr) {
  const [startTime, endTime] = rangeStr.split("-")
  const targetTime = dayjs(timeStr, "HH:mm")
  const start = dayjs(startTime, "HH:mm")
  const end = dayjs(endTime, "HH:mm")

  return targetTime.isAfter(start) && targetTime.isBefore(end)
}
// 05月13日周二 格式日期
const formattedTime = computed(() => {
  return dayjs(formInline.value.departureDate).format("MM月DD日 ddd")
})

let activeNameTmp = computed(() => {
  return parseInt(
    dayjs(formInline.value.departureDate)
      .startOf("day")
      .diff(dayjs().startOf("day"), "day")
  )
})

watch(activeNameTmp, (val) => {
  activeName.value = val <= 15 ? val : 0
})

watch(activeName, (val) => {
  formInline.value.departureDate = days[val].format("YYYY-MM-DD")
})
// 计算当前出发站点
const from = computed(() => {
  const tmp = allStations.value.filter(
    (item) => item.code === formInline.value.fromStation
  )
  return tmp
})

// 计算当前出发站点
const to = computed(() => {
  const tmp = allStations.value.filter(
    (item) => item.code === formInline.value.toStation
  )
  return tmp
})

// 出发车站多选框
const checkDepartureStationAll = ref(false)
// 选中的出发车站
const checkedDepartureStation = ref([])
const handleCheckDepartureStationAllChange = (val) => {
  checkedDepartureStation.value = val ? departureStationList.value : []
}
const handleCheckedDepartureStationChange = (value) => {
  judgeType.value.dS = value
  const checkedCount = value.length
  checkDepartureStationAll.value =
    checkedCount === departureStationList.value.length
}

// 车次类型多选框
const checkTrainBrandAll = ref(false)
// 选中的车次类型
const checkedTrainBrand = ref([])
const handleCheckTrainBrandAllChange = (val) => {
  checkedTrainBrand.value = val ? trainBrandList.value : []
}
const handleCheckedTrainBrandChange = (value) => {
  filterTrainListByTrainBrand(value)
  const checkedCount = value.length
  checkTrainBrandAll.value = checkedCount === trainBrandList.value.length
  if (checkedCount === 0) {
    trainList.value = trainListTmp.value
  }
}
// 根据选中的车次筛选车票
const filterTrainListByTrainBrand = (value) => {
  let brands = []
  for (let val of value) {
    TRAIN_BRAND_LIST.forEach((item) => {
      if (item.label === val) {
        brands.push(item.code + "")
      }
    })
  }
  judgeType.value.tBL = brands
}

// 到达车站多选框
const checkArrivalStationAll = ref(false)
// 选中的到达车站
const checkedArrivalStation = ref([])
const handleCheckArrivalStationAllChange = (val) => {
  checkedArrivalStation.value = val ? arrivalStationList.value : []
}
const handleCheckedArrivalStationChange = (value) => {
  judgeType.value.aS = value
  const checkedCount = value.length
  checkArrivalStationAll.value =
    checkedCount === arrivalStationList.value.length
}

// 车次席别
const checkseatClassTypeListAll = ref(false)
// 选中的车次席别
const checkedseatClassTypeList = ref([])
const handleCheckseatClassTypeListAllChange = (val) => {
  checkedseatClassTypeList.value = val ? seatClassTypeList.value : []
}
const handleCheckedseatClassTypeListChange = (value) => {
  filterTrainListBySeatClassType(value)
  const checkedCount = value.length
  checkseatClassTypeListAll.value =
    checkedCount === seatClassTypeList.value.length
}

// 根据选中的车次筛选车票
const filterTrainListBySeatClassType = (value) => {
  let seatTypes = []
  for (let val of value) {
    SEAT_CLASS_TYPE_LIST.forEach((item) => {
      if (item.label === val) {
        seatTypes.push(item.code)
      }
    })
  }
  judgeType.value.sCT = seatTypes
}

// 查询车票
const searchHandle = async () => {
  const resp = await queryTicket(formInline.value)
  if (resp) {
    trainList.value = resp.data.trainList
    trainListTmp.value = trainList.value
    // 筛选当前的车次类型
    trainBrandList.value = []
    for (let i of resp.data.trainBrandList) {
      let tmp = TRAIN_BRAND_LIST.filter((item) => item.code === i)
      trainBrandList.value.push(tmp[0].label)
    }
    // 当前的出发车站
    departureStationList.value = resp.data.departureStationList
    // 当前的到达车站
    arrivalStationList.value = resp.data.arrivalStationList
    // 筛选当前的席别类型
    seatClassTypeList.value = []
    for (let i of resp.data.seatClassTypeList) {
      let tmp = SEAT_CLASS_TYPE_LIST.filter((item) => item.code === i)
      seatClassTypeList.value.push(tmp[0].label)
    }
  }
}

// 查询所有站点
onMounted(async () => {
  searchHandle()
  const resp = await queryAllStation()
  if (resp) {
    allStations.value = resp.data
  }
})
</script>
<style scoped lang="scss">
.main-container {
  display: flex;
  flex-direction: column;
  .breadcrumb {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .breadcrumb-logo {
      .iconfont {
        font-size: 14px;
      }
      span {
        margin-left: 4px;
        color: rgba(0, 0, 0, 0.45);
      }
    }
    .breadcrumb-separator {
      margin: 0 8px;
    }
    .breadcrumb-link {
      display: flex;
      align-items: center;
      .iconfont {
        font-size: 18px;
      }
      span {
        margin-left: 4px;
        color: rgba(0, 0, 0, 0.85);
      }
    }
  }
  .main-content {
    display: flex;
    flex-direction: column;
    .card-body2 {
      border: 1px solid #1890ff;
      border-radius: 4px;
      background-color: #fff;
      margin-bottom: 16px;
      .card-content {
        display: flex;
        margin: 24px;
        .content-left {
          flex: 0 0 83.33333333%;
          max-width: 83.33333333%;
          .trainbrand {
            display: flex;
            align-items: center;
            flex-wrap: nowrap;
            .title {
              font-weight: bold;
              font-size: 14px;
              margin-right: 10px;
            }
            .el-checkbox:last-of-type {
              margin-right: 30px;
            }
          }
        }
        .content-right {
          flex: 0 0 16.66666667%;
          max-width: 16.66666667%;
          display: flex;
          span {
            max-width: 33.33333333%;
            height: 32px;
            line-height: 32px;
            color: rgba(0, 0, 0, 0.85);
            margin-right: 10px;
          }
          .el-select {
            max-width: 66.66666667%;
          }
        }
      }
      ::v-deep .el-tabs--border-card {
        border-radius: 4px 4px 0 0;
        .el-tabs__header {
          border-radius: 4px 4px 0 0;
        }
      }

      .el-tabs--border-card {
        border: none;
        margin-top: 1px;
        margin-bottom: 16px;
      }
      ::v-deep .el-tabs {
        .el-tabs__content {
          display: none;
        }
        .el-tabs__nav {
          width: 100%;
          .el-tabs__item {
            flex: 1;
          }
          .el-tabs__item.is-active {
            flex: 1.5;
          }
        }
      }
    }
    .card-body {
      padding: 24px;
      border: 1px solid #1890ff;
      border-radius: 4px;
      background-color: #fff;
      margin-bottom: 16px;
      .retweet {
        margin-right: 20px;
        line-height: 32px;
        .icon-retweet {
          font-size: 20px;
          color: rgb(25, 144, 255);
          cursor: pointer;
        }
      }
      .el-form {
        display: flex;
        align-content: center;
        .el-form-item {
          margin-bottom: 0px;
        }
      }
      .demo-form-inline .el-input {
        --el-input-width: 150px;
      }
      .demo-form-inline .el-select {
        --el-select-width: 150px;
      }
    }
    .space-item {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      .city-name {
        padding: 0 10px;
        font-weight: bolder;
      }
    }
    .list-table {
      margin-bottom: 16px;
    }
    .description {
      padding: 15px 15px;
      background-color: #fffbe6;
      border: 1px solid #ffe58f;
      color: rgba(0, 0, 0, 0.85);
    }
  }
}
</style>
